import socket
import network
import time

ap = network.WLAN(network.AP_IF)
ap.active(True)
ap.config(essid="myLED", authmode=1) #authmode=1 == no pass


HTML = b"""\
HTTP/1.0 200 OK

<!doctype html>
<html>
    <head>
        <title>WiFi Portal</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta charset="utf8">
    </head>
    <body>
        <h2 class="title">Configure Network Settings</h2>
        <form action="/network">
            Network Name: <input class="input" type="text" name="ssid">
            <br>
            Password: <input class="input" type="text" name="password">
            <br>
            <input type="submit" value="Submit">
        </form>
    </body>
</html>
"""

class DNSQuery:
  def __init__(self, data):
    self.data=data
    self.dominio=''

    print("正在读取数据 报数据...")
    m = data[2] # ord(data[2])
    tipo = (m >> 3) & 15   # Opcode bits
    if tipo == 0:                     # Standard query
      ini=12
      lon=data[ini] # ord(data[ini])
      while lon != 0:
        self.dominio+=data[ini+1:ini+lon+1].decode("utf-8") +'.'
        ini+=lon+1
        lon=data[ini] #ord(data[ini])

  def respuesta(self, ip):
    packet=b''
    print("Resposta {} == {}".format(self.dominio, ip))
    if self.dominio:
      packet+=self.data[:2] + b"\x81\x80"
      packet+=self.data[4:6] + self.data[4:6] + b'\x00\x00\x00\x00'   # Questions and Answers Counts
      packet+=self.data[12:]                                         # 原始域名问题
      packet+= b'\xc0\x0c'                                             # 指向域名的指针
      packet+= b'\x00\x01\x00\x01\x00\x00\x00\x3c\x00\x04'             # 响应类型、ttl和资源数据长度->4字节
      packet+=bytes(map(int,ip.split('.'))) # 4 bytes of IP
    return packet

def start():
    # DNS Server
    ip=ap.ifconfig()[0]
    print('DNS服务: dom.query. 60 IN A {:s}'.format(ip))

    udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udps.setblocking(False)
    udps.bind(('',53))

    # Web Server
    s = socket.socket()
    ai = socket.getaddrinfo(ip, 80)
    print("Web绑定:", ai)
    addr = ai[0][-1]

    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(addr)
    s.listen(1)
    s.settimeout(2)
    print("Web监听 http://{}:80/".format(ip))

    counter = 0

    while 1:
        # DNS Loop
        try:
            data, addr = udps.recvfrom(1024)
            print("输入数据报...")
            p=DNSQuery(data)
            udps.sendto(p.respuesta(ip), addr)
            print('回应: {:s} -> {:s}'.format(p.dominio, ip))
        except:
            print("无 数据报")
        # Web loop
        try:
            res = s.accept()
            client_sock = res[0]
            client_addr = res[1]
            #print("Client address:", client_addr)
            #print("Client socket:", client_sock)

            client_stream = client_sock

            print("Request:")
            req = client_stream.readline()
            print(req)
            while True:
                h = client_stream.readline()
                if h == b"" or h == b"\r\n" or h is None:
                    break
            #     print(h)

            request_url = req[4:-11] # GET /xxxxx?xxxx
            api = request_url[:9]
            if api == b'/network?':
                # 取尾部
                params = request_url[9:]
                print("取尾部 network--->", params,type(params))
                strarg = params.decode()
                wifi = strarg.split('&')
                print("network--->",wifi)
                sta = network.WLAN(network.STA_IF)
                sta.active(True)
                sta.connect(wifi[0][5], wifi[1][9])
                time.sleep(5)
                if sta.isconnected():
                    break
                else:
                    print("连接失败")

            client_stream.write(HTML.format(counter))

            client_stream.close()
            counter += 1
        except:
            print("web超时。。。继续。。。")
        print("loop")
        time.sleep_ms(300)

    udps.close()